<template>
	<picker mode="selector" :value="currentIndex" :range="range" :range-key="rangeKey" @change="handleChange">
		<slot :label="label"></slot>
	</picker>
</template>
<script>
	export default {
		props: {
			range: {
				type: Array,
				default: () => [],
			},
			strokeWidth: {
				type: Number,
				default: 10,
			},
			activeColor: {
				type: String,
				default: '#42b983',
			},
			rangeKey: {
				type: String,
				default: ''
			},
			rangeValue: {
				type: String,
				default: ''
			},
			modelValue: {
				type: [String, Number],
				default: ''
			},
			value: {
				type: [String, Number],
				default: ''
			},
		},
		model: {
			prop: 'value',
			event: 'input'
		},
		computed: {
			innerValue() {
				// #ifdef VUE2
				return this.value
				// #endif
				// #ifdef VUE3
				return this.modelValue
				// #endif
			}
		},
		data() {
			return {
				currentIndex: 0,
				label: ''
			}
		},
		watch: {
			innerValue(newVal, oldVal) {
				this.currentIndex = this.getIndex(newVal)
				this.label = this.range[this.currentIndex][this.rangeKey]
			}
		},
		methods: {
			handleChange: function(e) {
				let index = e.detail.value
				this.currentIndex = index
				this.label = this.range[this.currentIndex][this.rangeKey]
				this.$emit('update:modelValue', this.getValue(index))
				this.$emit('input', this.getValue(index))
				this.$emit('change', e)
			},
			getValue: function(index) {
				const value = this.range[index][this.rangeValue]
				return value
			},
			getIndex: function(val) {
				let index = 0
				this.range.some((item, i) => {
					if (item[this.rangeValue] === val) {
						index = i
					}
					console.log(item[this.rangeValue], val)
					return item[this.rangeValue] === val
				})
				return index
			},
			getLabel: function(index) {
				const label = this.range[index][this.rangeKey]
				return label
			}
		}
	}
</script>
<style>
</style>